import dictApi from "@/api/system/dict";

const TYPES = {
  menu: 'menu',//[]
  menuTree: 'menuTree',//[]
  dictType: 'dictType',//{type1:{},type2:{}}
  dictList: 'dictList'//{type1:{id1:{},id2:{}},type2:{id1:{},id2:{}}}
};
let typeList = {};
let dataList = {};
export default {
  clear() {
    for (let key in TYPES) {
      sessionStorage.removeItem(key);
    }
  },

  /**
   * 菜单管理缓存
   * @param menuList
   */
  setMenuList(menuList) {
    sessionStorage.setItem(TYPES.menu, JSON.stringify(menuList));
  },
  getMenuList() {
    let dataList = this._getResultData(TYPES.menu)
    return dataList || [];
  },
  setMenuTreeList(menuTreeList) {
    sessionStorage.setItem(TYPES.menuTree, JSON.stringify(menuTreeList));
  },
  getMenuTreeList() {
    let dataList = this._getResultData(TYPES.menuTree)
    return dataList || [];
  },

  /**
   * 数据字典管理缓存
   * @returns {Promise<void>}
   */
  async initDict() {
    //字典类型缓存
    let res = await dictApi.typeList({pageSize: 999});
    if (!res) {
      return
    }
    let data = res.data && res.data.rows || [];
    let typeList = {};
    data.forEach(item => {
      typeList[item.id] = item;
    });
    sessionStorage.setItem(TYPES.dictType, JSON.stringify(typeList));


    //字典列表缓存
    let dataList = {};
    res = await dictApi.list();
    res.data.forEach(item => {
      let type = item.type;
      if (!dataList[type]) {
        dataList[type] = {};
      }
      dataList[type][item.id] = item;
    })
    sessionStorage.setItem(TYPES.dictList, JSON.stringify(dataList));
  },
  getDictType() {
    let dataList = this._getResultData(TYPES.dictType);
    return dataList || {}
  },
  getDictList(type) {
    let dataList = this._getResultData(TYPES.dictList);
    let result = dataList[type]
    return result || {};
  },

  /**
   * 获取缓存数据
   * @param key
   * @returns {any}
   * @private
   */
  _getResultData(key) {
    let dataList = sessionStorage.getItem(key);
    if (dataList == 'undefined' || dataList == 'null') {
      dataList = {};
    } else {
      dataList = JSON.parse(dataList);
    }
    return dataList;
  }
}
